package org.novaacropole.util;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;

import javax.mail.Folder;
import javax.mail.Header;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Store;

import org.apache.commons.validator.EmailValidator;
import org.apache.log4j.Logger;
import org.novaacropole.envio.Envio;
import org.novaacropole.grupo.Grupo;

public class POPClient implements Runnable {

	static Logger log = Logger.getLogger(POPClient.class);

	@Override public void run() {
		try {
			List<String> mimes = bouncesMimes();
			if (mimes.size() > 0) {
				DAO.begin();
				List<Envio> envios = Envio.findEnviosByMimesNotBounced(mimes);
				for (Envio envio : envios) {
					envio.setBounced(true);
					envio.save();
					for (Grupo grupo : envio.getEmail().getGrupos()) {
						grupo.getEmails().remove(envio.getEmail());
						grupo.save();
					}
				}
				DAO.commit();
			}
		} catch (Throwable t) {
			log.error("POP3", t);
			DAO.rollback();
		} finally {
			DAO.close();
		}

	}

	public List<String> bouncesMimes() throws Exception {

		Properties props = new Properties();
		props.setProperty("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
		props.setProperty("mail.pop3.socketFactory.fallback", "false");
		props.setProperty("mail.pop3.port", "995");
		props.setProperty("mail.pop3.socketFactory.port", "995");

		String host = "pop.gmail.com";
		String username = "novaacropolebueno";
		String password = "bueno1000";

		List<String> bouncesMime = new ArrayList<String>();

		Store store = null;
		Folder inbox = null;
		try {
			Session session = Session.getDefaultInstance(props, null);
			store = session.getStore("pop3");
			store.connect(host, username, password);
			inbox = store.getFolder("INBOX");
			inbox.open(Folder.READ_ONLY);
			Message[] messages = inbox.search(new GmailBounceSearch());
			for (Message message : messages) {
				Enumeration<?> headers = message.getAllHeaders();
				while (headers.hasMoreElements()) {
					Header header = (Header) headers.nextElement();
					System.out.println(header.getName() + "		" + header.getValue());
					if (header.getName().equals("X-Failed-Recipients")) {
						String email = header.getValue();
						if (EmailValidator.getInstance().isValid(email))
							bouncesMime.add(getMime((String) message.getContent()));
					}
				}
			}
		} finally {
			inbox.close(false); // close_bu_not_remove_messages
			store.close();
		}
		return bouncesMime;

	}

	public String getMime(String message) {
		String messageId = "Message-ID: ";
		int index = message.indexOf(messageId) + messageId.length();
		return message.substring(index, message.indexOf(">", index) + 1);
	}
}
